<template>
  <div class="notifications-page">
    <div class="container py-4">
      <!-- 通知过滤 -->
      <div class="notification-filters mb-4">
        <div class="filter-tabs">
          <button 
            v-for="filter in filters" 
            :key="filter.key"
            @click="setFilter(filter.key)"
            :class="['filter-btn', { active: activeFilter === filter.key }]"
          >
            {{ filter.label }}
          </button>
        </div>
      </div>

      <!-- 通知列表 -->
      <div class="notifications-container">
        <!-- 加载状态 -->
        <div v-if="loading && notifications.length === 0" class="text-center py-5">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">加载中...</span>
          </div>
          <p class="mt-2 text-muted">正在加载通知...</p>
        </div>

        <!-- 通知列表 -->
        <div v-else-if="notifications.length > 0" class="notification-list">
          <div
            v-for="notification in filteredNotifications"
            :key="notification.id"
            :class="['notification-item', { 'unread': notification.isRead === 0 }]"
          >
            <div class="notification-content">
              <div class="notification-header">
                <div class="notification-title">
                  <span :class="getTypeIcon(notification.type)" class="type-icon me-2"></span>
                  {{ notification.title }}
                </div>
                <div class="notification-meta">
                  <span :class="['level-badge', getLevelClass(notification.level)]">
                    {{ getLevelText(notification.level) }}
                  </span>
                  <span class="notification-time">{{ formatTime(notification.createdTime) }}</span>
                </div>
              </div>
              <div class="notification-body">
                <p class="notification-text">{{ notification.content }}</p>
                <div v-if="notification.actionUrl" class="notification-actions">
                  <a :href="notification.actionUrl" class="btn btn-sm btn-primary">查看详情</a>
                </div>
              </div>
            </div>
            <div class="notification-operations">
              <button
                v-if="notification.isRead === 0"
                @click="markAsRead(notification)"
                class="btn btn-sm btn-outline-primary"
                :disabled="markingRead.has(notification.id!)"
              >
                <i class="fas fa-check me-1"></i>
                {{ markingRead.has(notification.id!) ? '标记中...' : '标为已读' }}
              </button>
              <span v-else class="read-status">
                <i class="fas fa-check-circle text-success"></i>
                已读
              </span>
            </div>
          </div>
        </div>

        <!-- 无数据提示 -->
        <div v-else class="text-center py-5">
          <i class="fas fa-bell-slash fa-3x text-muted mb-3"></i>
          <p class="text-muted">{{ activeFilter === 'all' ? '暂无通知' : '暂无相关通知' }}</p>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-section mt-4" v-if="totalPages > 1">
        <nav aria-label="通知分页">
          <ul class="pagination justify-content-center">
            <li class="page-item" :class="{ disabled: currentPage <= 1 }">
              <button class="page-link" @click="changePage(currentPage - 1)" :disabled="currentPage <= 1">
                上一页
              </button>
            </li>
            <li 
              v-for="page in getPageNumbers()" 
              :key="page"
              class="page-item" 
              :class="{ active: page === currentPage }"
            >
              <button class="page-link" @click="changePage(page)">{{ page }}</button>
            </li>
            <li class="page-item" :class="{ disabled: currentPage >= totalPages }">
              <button class="page-link" @click="changePage(currentPage + 1)" :disabled="currentPage >= totalPages">
                下一页
              </button>
            </li>
          </ul>
        </nav>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useUserStore } from '@/stores/user'
import { 
  getUserNotifications, 
  getUnreadNotificationCount,
  markNotificationAsRead,
  markAllNotificationsAsRead
} from '@/api/notification'
import type { Notification } from '@/types/notification'
import { NotificationType, NotificationLevel } from '@/types/notification'
import { Message } from '@/utils/message'

// Store
const userStore = useUserStore()

// 响应式数据
const notifications = ref<Notification[]>([])
const loading = ref(false)
const markingAllRead = ref(false)
const markingRead = ref(new Set<number>())
const currentPage = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)
const unreadCount = ref(0)
const activeFilter = ref('all')

// 过滤选项
const filters = [
  { key: 'all', label: '全部' },
  { key: 'unread', label: '未读' },
  { key: 'system', label: '系统通知' },
  { key: 'order', label: '订单通知' },
  { key: 'product', label: '商品通知' },
  { key: 'security', label: '安全通知' }
]

// 计算属性
const totalPages = computed(() => Math.ceil(totalCount.value / pageSize.value))

const filteredNotifications = computed(() => {
  if (activeFilter.value === 'all') return notifications.value
  if (activeFilter.value === 'unread') return notifications.value.filter(n => n.isRead === 0)
  
  const typeMap: Record<string, number> = {
    'system': NotificationType.SYSTEM,
    'order': NotificationType.ORDER,
    'product': NotificationType.PRODUCT,
    'security': NotificationType.SECURITY
  }
  
  const filterType = typeMap[activeFilter.value]
  return notifications.value.filter(n => n.type === filterType)
})

// 获取通知类型图标
const getTypeIcon = (type: number) => {
  const iconMap: Record<number, string> = {
    [NotificationType.SYSTEM]: 'fas fa-cog',
    [NotificationType.ORDER]: 'fas fa-shopping-cart',
    [NotificationType.PRODUCT]: 'fas fa-box',
    [NotificationType.SECURITY]: 'fas fa-shield-alt'
  }
  return iconMap[type] || 'fas fa-bell'
}

// 获取级别样式
const getLevelClass = (level: number) => {
  const classMap: Record<number, string> = {
    [NotificationLevel.NORMAL]: 'level-normal',
    [NotificationLevel.IMPORTANT]: 'level-important',
    [NotificationLevel.URGENT]: 'level-urgent'
  }
  return classMap[level] || 'level-normal'
}

// 获取级别文本
const getLevelText = (level: number) => {
  const textMap: Record<number, string> = {
    [NotificationLevel.NORMAL]: '普通',
    [NotificationLevel.IMPORTANT]: '重要',
    [NotificationLevel.URGENT]: '紧急'
  }
  return textMap[level] || '普通'
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return date.toLocaleDateString('zh-CN')
}

// 加载通知列表
const loadNotifications = async () => {
  if (!userStore.userInfo?.id) return
  
  loading.value = true
  try {
    const response = await getUserNotifications(currentPage.value, pageSize.value, userStore.userInfo.id)
    notifications.value = response.data.records
    totalCount.value = response.data.total
    
    // 同时获取未读数量
    const unreadResponse = await getUnreadNotificationCount(userStore.userInfo.id)
    unreadCount.value = unreadResponse.data
  } catch (error) {
    console.error('加载通知失败:', error)
    Message.error('加载通知失败')
  } finally {
    loading.value = false
  }
}

// 设置过滤器
const setFilter = (filter: string) => {
  activeFilter.value = filter
}

// 分页
const changePage = (page: number) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  loadNotifications()
}

const getPageNumbers = () => {
  const pages: number[] = []
  const start = Math.max(1, currentPage.value - 2)
  const end = Math.min(totalPages.value, currentPage.value + 2)
  
  for (let i = start; i <= end; i++) {
    pages.push(i)
  }
  return pages
}

// 标记单个通知为已读
const markAsRead = async (notification: Notification) => {
  if (!notification.id || notification.isRead === 1) return
  
  markingRead.value.add(notification.id)
  try {
    await markNotificationAsRead(notification.id)
    notification.isRead = 1
    notification.readTime = new Date().toISOString()
    unreadCount.value = Math.max(0, unreadCount.value - 1)
    Message.success('已标记为已读')
  } catch (error) {
    console.error('标记已读失败:', error)
    Message.error('标记已读失败')
  } finally {
    markingRead.value.delete(notification.id)
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  if (!userStore.userInfo?.id || unreadCount.value === 0) return
  
  markingAllRead.value = true
  try {
    await markAllNotificationsAsRead(userStore.userInfo.id)
    notifications.value.forEach(n => {
      if (n.isRead === 0) {
        n.isRead = 1
        n.readTime = new Date().toISOString()
      }
    })
    unreadCount.value = 0
    Message.success('已全部标记为已读')
  } catch (error) {
    console.error('全部标记已读失败:', error)
    Message.error('全部标记已读失败')
  } finally {
    markingAllRead.value = false
  }
}

// 监听页面变化
watch(currentPage, () => {
  loadNotifications()
})

// 初始化
onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notifications-page {
  background: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.page-header {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title {
  color: #333;
  font-weight: 600;
}

.notification-stats .badge {
  font-size: 12px;
}

.notification-filters {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.filter-tabs {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 8px 16px;
  border: 1px solid #dee2e6;
  background: white;
  color: #666;
  border-radius: 20px;
  font-size: 14px;
  transition: all 0.3s ease;
  cursor: pointer;
}

.filter-btn:hover,
.filter-btn.active {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.notifications-container {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.notification-list {
  border-radius: 8px;
  overflow: hidden;
}

.notification-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  transition: all 0.3s ease;
  position: relative;
}

.notification-item:last-child {
  border-bottom: none;
}

.notification-item.unread {
  background: #f8f9ff;
  border-left: 4px solid #007bff;
}

.notification-item.unread::before {
  content: '';
  position: absolute;
  top: 15px;
  left: 10px;
  width: 8px;
  height: 8px;
  background: #007bff;
  border-radius: 50%;
}

.notification-content {
  flex: 1;
  margin-right: 15px;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.notification-title {
  font-weight: 600;
  color: #333;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.type-icon {
  color: #666;
  width: 16px;
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 12px;
}

.level-badge {
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 500;
}

.level-normal {
  background: #e3f2fd;
  color: #1976d2;
}

.level-important {
  background: #fff3e0;
  color: #f57c00;
}

.level-urgent {
  background: #ffebee;
  color: #d32f2f;
}

.notification-time {
  color: #999;
}

.notification-body {
  margin-top: 8px;
}

.notification-text {
  color: #666;
  line-height: 1.5;
  margin: 0 0 10px 0;
  font-size: 14px;
}

.notification-actions {
  margin-top: 10px;
}

.notification-operations {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  min-width: 100px;
}

.read-status {
  color: #28a745;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .notification-item {
    flex-direction: column;
    gap: 10px;
  }
  
  .notification-operations {
    align-items: flex-start;
    flex-direction: row;
    min-width: auto;
  }
  
  .notification-header {
    flex-direction: column;
    gap: 5px;
    align-items: flex-start;
  }
  
  .filter-tabs {
    justify-content: center;
  }
  
  .filter-btn {
    padding: 6px 12px;
    font-size: 12px;
  }
}

@media (max-width: 576px) {
  .page-header {
    padding: 15px;
  }
  
  .header-actions {
    display: flex;
    flex-direction: column;
    gap: 5px;
  }
  
  .notification-filters {
    padding: 10px 15px;
  }
  
  .notification-item {
    padding: 15px;
  }
}
</style> 